//
//  AppDelegate.m
//  newKuiBa
//
//  Created by Lin Eidan on 14/6/13.
//  Copyright (c) 2014年 haomee. All rights reserved.
//

#import "AppDelegate.h"
#import "APService.h"
#import "LoginViewController.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "Header.h"
#import "WXApi.h"
#import "QQApi.h"
#import "M3U8DownloadConfig.h"
#import <Frontia/Frontia.h>
#import "ShareView.h"
#import "LaunchViewController.h"


@interface AppDelegate()

#pragma mark -推送，标记程序是否在运行。
@property (assign, nonatomic) BOOL appIsRuning;

#pragma mark - 网络等待
@property (assign, nonatomic) int isWaitViewDisplay;
@property (strong, nonatomic) UIView *maskTopWaitView;
@property (strong, nonatomic) UIActivityIndicatorView *act;

#pragma mark - 分享
@property (strong, nonatomic) ShareView* shareView;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor =  ColorWithHex(0X000000);
    
    [self initViewController];
    [self initOther];
    
    [self.window makeKeyAndVisible];
    [self performSelector:@selector(initStatisticsWithOptions:) withObject:launchOptions afterDelay:0.5];
    return YES;
}

#pragma mark - Init ShareView
-(void)initShareViewWithUrl:(NSString *)url andWithTitle:(NSString *)title andWithInfo:(NSString *)info andWithImageUlr:(NSString *)imageUrl andIsSuccess:(Completion)completion
{
    if([[AFGetData sharedInstance] theNetworkTypeIsNone])
    {
        [PopTips tipsAtTop:self.rootNav.view Msg:NotifyNoNet];
        return;
    }
    if([[kHandle sharedInstance] isShowTrueView])
    {
        self.shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height)];
        [self.window addSubview:self.shareView];
        [self.shareView showWithUrl:url andWithTitle:title andWithInfo:info andWithImageUrl:imageUrl andSuccess:completion];
    }
    else{
        
        FrontiaShareContent *content = [[FrontiaShareContent alloc] init];
        content.url = ShareUrl;//必须，分享的链接
        content.description = NotifyMessage;//必须，分享的描述
        content.title = ShareTitle;//必须，分享的标题
        
        
        
        [[Frontia getShare] shareWithPlatform:FRONTIA_SOCIAL_SHARE_PLATFORM_SMS content:content supportedInterfaceOrientations:UIInterfaceOrientationMaskAllButUpsideDown isStatusBarHidden:NO cancelListener:^{
            
        } failureListener:^(int errorCode, NSString *errorMessage) {
            [PopTips tips:self.rootNav.view Msg:NotifyShareError];
        } resultListener:^{
            [PopTips tips:self.rootNav.view Msg:NotifyShareSuccess];
        }];
        
    }
}

#pragma mark - Init View Controller
- (void) initViewController
{
    self.rootNav = [[UINavigationController alloc] init];
    self.homeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    [self.rootNav setViewControllers:@[self.homeViewController]];
    self.rootNav.view.frame= [[UIScreen mainScreen] bounds];
    self.rootNav.view.backgroundColor = [UIColor blackColor];
    self.rootNav.navigationBar.hidden = YES;
    self.rootNav.navigationBar.barStyle = UIBarStyleBlack;  //解决preferredStatusBarStyle不执行问题
    [self.window setRootViewController:self.rootNav];
    
    //loading movie loading movie
    LaunchViewController *launchVC = [[LaunchViewController alloc] init];
    [self.rootNav pushViewController:launchVC animated:NO];
}


-(void)initOther{
    [[UserObj sharedInstance] firstInstallAPPHandle];
    [self initDownload];
    [kHandle sharedInstance];
}

//统计 第三方登录，分享，推送。
-(void)initStatisticsWithOptions:(NSDictionary *)launchOptions{
    
    //all
    [Frontia initWithApiKey:BaiDuApiKey];
    
    //统计
    FrontiaStatistics *statistics = [Frontia getStatistics];
    [statistics startWithReportId:BaiDuReportKey];
    
    //登录授权
    FrontiaAuthorization * authorization = [Frontia getAuthorization];
    [authorization enableSinaWeiboSSOWithSinaWeiboApiKey:SinaAppKey];
    [authorization enableQQSSOWithQQApiKey:QQAppKey];
    
    //JPush
    [self initJPushWithOptions:launchOptions];
    
    [self initWaitView];
}

#pragma mark - 下载
-(void) initDownload{
    
    NSString *videoDownLoadPath = [LocalFileManage getPathInsideLibraryCachesFolder:kPathVideoDownload];
    if (![LocalFileManage isExistFile:videoDownLoadPath]) {
        [LocalFileManage createFolder:videoDownLoadPath];
    }
    
    //防止意外退出
    [[DownloadVideoManager sharedInstance] performSelector:@selector(handleTheLastTerminate) withObject:nil afterDelay:0.0];
}

-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{
    self.backgroundSessionCompletionHandler = completionHandler;
    [[DownloadVideoManager sharedInstance] performSelector:@selector(backgrondDownloadOneTaskComplete) withObject:nil afterDelay:0.8];
}

#pragma -mark  APP
- (void)applicationWillResignActive:(UIApplication *)application
{
    self.appIsRuning = NO;  //进入后台。
    
    if ([self.rootNav.topViewController isKindOfClass:[LaunchViewController class]]) { //如果还在播放loading动画，然后进入后台了，要把loading动画干掉，否则再次进来后，就移除不掉。
        LaunchViewController *launchVC = (LaunchViewController *)self.rootNav.topViewController;
        [launchVC handleWhenGoBack];
    }

    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    //push tag 重新上传
    [self handleThePushRelatedAfterApplicationDidBecomeActive:application];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    [self parse:url application:application];
    
    //分享后，返回本客户端，才能调用成功或者失败的回调。
    FrontiaShare *share = [Frontia getShare];
    return [share handleOpenURL:url];
}

#pragma mark - JPush
-(void)initJPushWithOptions:(NSDictionary *)launchOptions{
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert) categories:nil];
    [APService setupWithOption:launchOptions];
}

-(void)handleThePushRelatedAfterApplicationDidBecomeActive:(UIApplication *)application{
    if (application && self) {
        self.appIsRuning = YES;  //只能在这边设置，，不能在WillEnterForeground函数中设置，而且只能是第一句。
        application.applicationIconBadgeNumber = 0 ;
        [self performSelector:@selector(handleThePushTagDelay) withObject:nil afterDelay:10];  //延迟一下，才能正确。
    }
}

-(void)handleThePushTagDelay{
    //每次进入到前台，将收藏的最新id们，传给push，让其可以推送。
    //    NSArray *tempArray = [UserDataBasic getCollectDataVideoIdWithNeedIsOver:NO];
    //    NSSet *tempSet = [NSSet setWithArray:tempArray];
    //    [APService setTags:tempSet alias:[Common getOpenUDID] callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
}

//push , 设置tag成功的回调。。
- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
    //    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
}

//接收到通知后的处理，还是这个函数靠谱
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [APService handleRemoteNotification:userInfo];
    if (self.appIsRuning) {   //程序正在运行中，就返回。
        return;
    }
    //    if ([userInfo objectForKey:HttpContentId]) {
    //    }
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [APService registerDeviceToken:deviceToken];
}

#pragma mark - 支付宝

//独立客户端回调函数
//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
//
//
//	return YES;
//}

- (void)parse:(NSURL *)url application:(UIApplication *)application {
    
    //结果处理
    
    AlixPayResult* result = [self handleOpenURL:url];
    NSLog(@"result = %@",result);
	if (result)
    {
		
		if (result.statusCode == 9000)
        {
            
            NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleSuccess
                                                              title:NotifyTitlSuceess
                                                            message:NotifyVipSuccess
                                                           delegate:nil];
            [alert show];
            
            
            
            
        }
        else
        {
            //交易失败
            
            NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleError
                                                              title:NotifyNormal
                                                            message:NotifyVipError
                                                           delegate:nil];
            [alert show];
        }
    }
    
}


- (AlixPayResult *)resultFromURL:(NSURL *)url {
	NSString * query = [[url query] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
#if ! __has_feature(objc_arc)
    return [[[AlixPayResult alloc] initWithString:query] autorelease];
#else
	return [[AlixPayResult alloc] initWithString:query];
#endif
}

- (AlixPayResult *)handleOpenURL:(NSURL *)url {
	AlixPayResult * result = nil;
	
	if (url != nil && [[url host] compare:@"safepay"] == 0) {
		result = [self resultFromURL:url];
	}
    
	return result;
}

#pragma mark -网络等待
-(void)initWaitView{
    self.isWaitViewDisplay=0;
    int width = 80;
    int height = 80;
    int offset_x = (self.rootNav.view.width-width)/2;
    int offset_y = (self.rootNav.view.height-height)/2;
    
    self.maskTopWaitView=[[UIView alloc] initWithFrame:CGRectMake(offset_x,offset_y, width, height)];
    [self.maskTopWaitView setBackgroundColor:[UIColor blackColor]];
    self.maskTopWaitView.layer.cornerRadius = 10;
    
    self.act=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.act.left=(width-self.act.width)/2;
    self.act.top=(height-self.act.height)/2;
    [self.act startAnimating];
    [self.maskTopWaitView addSubview:self.act];
    
    self.allMaskView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Height, kScreen_Height)];
    self.allMaskView.backgroundColor = [UIColor blackColor];
    self.allMaskView.alpha=0.0;
    
}
-(void)displayWaitViewWithAllMaskView:(BOOL) isDisplayMaskView{
    if (self.isWaitViewDisplay == 0) {
        self.maskTopWaitView.alpha=0;
        
        if (isDisplayMaskView) {
            [self.rootNav.view addSubview:self.allMaskView];
        }
        [self.rootNav.view addSubview:self.maskTopWaitView];
        [UIView animateWithDuration:0.3 animations:^{
            self.allMaskView.alpha=0.3;
            self.maskTopWaitView.alpha=0.5;
        }];
        self.isWaitViewDisplay=1;
    }
}

-(void)hideWaitView{
    if (self.isWaitViewDisplay == 1) {
        [UIView animateWithDuration:0.3 animations:^{
            self.maskTopWaitView.alpha=0;
            self.allMaskView.alpha=0;
        }completion:^(BOOL finished) {
            [self.allMaskView removeFromSuperview];
            [self.maskTopWaitView removeFromSuperview];
        }];
        self.isWaitViewDisplay =0;
    }
}




@end
